package com.dmd.yikang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dmd.yikang.common.CustomException;
import com.dmd.yikang.entity.Category;
import com.dmd.yikang.entity.Medicine;
import com.dmd.yikang.entity.Setmeal;
import com.dmd.yikang.mapper.CategoryMapper;
import com.dmd.yikang.service.CategoryService;
import com.dmd.yikang.service.MedicineService;
import com.dmd.yikang.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author daimingdong
 * @version 1.0.0
 * create 2024/5/27 17:17
 * description
 * @title CategoryServiceImpl
 **/
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private MedicineService medicineService;

    @Autowired
    private SetmealService setmealService;
    /**
     * 根据id删除分类，删除之前需要进行判断
     * @param id
     */
    @Override
    public void remove(Long id) {
        LambdaQueryWrapper<Medicine> medicineLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //添加查询条件，根据分类id进行查询
        medicineLambdaQueryWrapper.eq(Medicine::getCategoryId,id);
        int count1 = medicineService.count(medicineLambdaQueryWrapper);

        //查询当前分类是否关联了药品，如果已经关联，抛出一个业务异常
        if (count1 > 0){
            //已经关联，抛出一个业务异常
            throw new CustomException("当前分类下关联了药品，不能删除");
        }

        //查询当前分类是否关联了药品组合，如果已经关联，抛出一个业务异常
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //添加查询条件，根据分类id进行查询
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId,id);
        int count2 = setmealService.count(setmealLambdaQueryWrapper);
        if (count2 > 0){
            //已经关联了药品这一回，抛出一个业务异常
            throw new CustomException("当前分类下关联了药品组合，不能删除");
        }

        //正常删除分类
        super.removeById(id);
    }
}
